package com.qf.admin.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.admin.entity.dto.Goods;
import com.qf.admin.entity.dto.GoodsColor;
import com.qf.admin.mapper.GoodsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class GoodsService extends ServiceImpl<GoodsMapper , Goods> {

    @Autowired
    private GoodsColorService goodsColorService;

    @Transactional(readOnly = true)
    public List<Goods> getAvaliableGoods() {
        QueryWrapper<Goods> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Goods::getIsDelete, "0");
        return this.list(wrapper);
    }

    @Transactional
    public void up(Long goodsId) {
        Goods goods = this.getById(goodsId);
        goods.setStatus(1);
        this.saveOrUpdate(goods);
    }

    @Transactional
    public void down(Long goodsId) {
        Goods goods = this.getById(goodsId);
        goods.setStatus(0);
        goods.setIsSeckill(0);
        this.saveOrUpdate(goods);
    }

    @Transactional
    public void secKill(Long goodsId) {
        Goods goods = this.getById(goodsId);
        if (goods.getIsSeckill() == 1){
            goods.setIsSeckill(0);
        }else{
            goods.setStatus(1);
            goods.setIsSeckill(1);
        }
        this.saveOrUpdate(goods);
    }

    @Transactional
    public void del(Long goodsId) {
        Goods goods = this.getById(goodsId);
        goods.setIsDelete(1);
        goods.setStatus(0);
        goods.setIsSeckill(0);
        goods.setDiscount(100);
        this.saveOrUpdate(goods);
    }

    @Transactional
    public void saveGoods(Goods goods, String color, String pic, String stock) {
        if(goods.getId() != null){
            goodsColorService.removeByGoodsId(goods.getId());
        }
        goods.setDiscount(100);
        goods.setIsSeckill(0);
        goods.setStatus(0);
        this.saveOrUpdate(goods);

        String[] colors = color.split("\\|");
        String[] pics = pic.split("\\|");
        String[] stocks = stock.split("\\|");

        List<GoodsColor> goodsColors = new ArrayList<>(color.length());

        for(int i = 0 ; i < colors.length ; i++){
            if(!"|".equals(colors[i])){
                GoodsColor goodsColor = new GoodsColor();
                goodsColor.setGoodsId(goods.getId());
                goodsColor.setColor(colors[i]);
                goodsColor.setPic(pics[i]);
                goodsColor.setStock(Integer.parseInt(stocks[i]));
                goodsColors.add(goodsColor);
            }
        }
        goodsColorService.saveBatch(goodsColors , goodsColors.size());
    }
}
